package com.xtedu.examproject.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    //验证码字符集
    private static final String CHAR_SET ="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    private static final int WIDTH = 120;//图片宽度
     private static final int HEIGHT = 40;//图片高度
     private static final int LENGTH = 4;//验证码长度

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //内存图像
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制干扰线
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            g.setColor(getRandomColor());
            g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT),
                    random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }

        // 生成随机验证码
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < LENGTH; i++) {
            char c = CHAR_SET.charAt(random.nextInt(CHAR_SET.length()));
            captcha.append(c);

            // 绘制字符
            g.setColor(getRandomColor());
            g.setFont(new Font("Arial", Font.BOLD, 24));
            g.drawString(String.valueOf(c), 20 + i * 20, 25);
        }

        // 将验证码存入session
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captcha.toString());

        // 设置响应内容类型为图片
        response.setContentType("image/jpeg");
        // 禁止缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 将图片写入响应输出流
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }
    // 生成随机颜色
    private Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200));
    }

}
